import {Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';


import {SignUpService} from "@sign-up/sign-up.service";
import {Subject} from "rxjs/Subject";
import {ActivatedRoute, Router} from "@angular/router";
import {FormBuilder, FormControl, FormGroup, Validator, Validators} from "@angular/forms";
import {TrainSignUpFormConfig, certificate, Trainkey} from "@sign-up/personal/train/train.model";
import {ValidationService} from "@shared/service/validator/validator.service";
import {Content} from "@shared/components/toolbar/toolbar-content";
import {ModalComponent} from "@shared/components/modal/modal.component";
import {PlaceParam} from "@shared/components/regio-picker/regio-picker.component";
import {ToolsService} from "@shared/service/tools/tools.service";
import {OrderService} from "@order/order.service";
import {SNSResult, TrainCourseSignupFields, TrainSignFormRespVO} from "@interface/index";
// import {TrainCourseSignupFields, TrainSignFormRespVO} from "@interface/train/train.model";
// import {SNSResult} from "@interface/interface/interface.model";

@Component({
  selector: 'seed-sign-up-train',
  templateUrl: './train.component.html',
  styleUrls: ['./train.component.scss'],
  encapsulation: ViewEncapsulation.None
})


export class SignUpTrainComponent implements OnInit {
  public signForm: FormGroup;
  public signing = false;
  // 选项
  public config: TrainSignUpFormConfig = new TrainSignUpFormConfig(Trainkey);
  public certificateArr = certificate;
  public countryGroup = [];
  public origin: {
    text: string;
    choose: PlaceParam;
  } = {
    text: '请选择籍贯',
    choose: new PlaceParam()
  };
  public fields: TrainCourseSignupFields[];
  public error = {  // 错误验证的状态
    parentNameIsError: false,
    nameIsError: false,
    phoneIsError: false,
    IDNumIsError: false,
    addressIsError: false,
    phoneIsRepeat: false,
  };
  public param: {
    orderNumber?: string,
    courseId?: string,
    goodsSku?: string,
    courseItemId?: string
  } = {};
  @ViewChild(Content) content;
  @ViewChild(ModalComponent) modal;
  private ngUnsubscribe: Subject<void> = new Subject<void>();
  constructor(private signUpService: SignUpService,
              private route: ActivatedRoute,
              private formBuilder: FormBuilder,
              private toolsSer: ToolsService,
              private router: Router,
              private orderService: OrderService
  ) {
    this.signForm = this.formBuilder.group({
      'name': ['', [Validators.required, ValidationService.nickNameSpaceValidator]],
      'phone': ['', [Validators.required, ValidationService.accountValidator]],
      // 'parentName': ['', [Validators.required]],
      // 'sex': ['', [Validators.required]],
      // 'certificate': ['', [Validators.required]],
      // 'nation': ['', [Validators.required]],
      // // 'origin': ['', [Validators.required]],
      // 'idNo': ['', [Validators.required, Validators.maxLength(30), ValidationService.nameValidator]],
      // 'birthday': ['', [Validators.required]],
      // 'address': ['', [Validators.required, Validators.maxLength(200)]],
      // 'nationality': ['', [Validators.required]],
      // 'weight': ['', [Validators.required, Validators.minLength(3)]],
      // 'height': ['', [Validators.required, Validators.minLength(3)]],
      // 'trait': ['', [Validators.required, Validators.maxLength(200)]],
      // 'sportItem': ['', [Validators.required, Validators.maxLength(200)]],
      // 'awardsItem': ['', [Validators.required, Validators.maxLength(200)]],
      // 'school': ['', [Validators.required, Validators.maxLength(200)]],
      // 'remark': ['', [Validators.required, Validators.maxLength(200)]],
    });
    // this.signForm.valueChanges.subscribe(res => {
    //   console.log(this.signForm);
    // });
  }
  ngOnInit() {
    this.dataInit();
  }
  // 选择证件类型
  certificateChange(val) {
    this.signForm.controls['idNo'].patchValue({'certificate': val});
  }
  // 选择国籍
  countryChange(val) {
    this.signForm.controls['nationality'].setValue(val);
  }
  dataInit() {
    this.route.queryParams.subscribe((param) => {
      this.param.courseId = param['courseId'];
      this.param.orderNumber = param['orderNumber'];
      this.param.goodsSku = param['goodsSku'];
      this.param.courseItemId = param['courseItemId'];
    });
    // this.app.loadingController().present('');
    this.signUpService.getTrainSignFields(this.param.courseId)
      .takeUntil(this.ngUnsubscribe)
      .subscribe((res: SNSResult<TrainSignFormRespVO>) => {
        // this.app.loadingController().dismiss();
        if (res.result === '0') {
          this.countryGroup = res.data.dictCountries;
          // this.formAdditional(res.data.fields);
          this.fields = res.data.fields;
          this.fields.forEach(e => {
            if (e.fieldName !== 'origin') {
              const control = this.addFormControl(e.fieldName);
              this.signForm.addControl(e.fieldName, control);
              this.config[e.fieldName].hasItem = true;
            }
            if (e.fieldName === 'origin') {
              this.config[e.fieldName].hasItem = true;
            }
          });
          if (this.config.idNo.hasItem ) {
            if ( this.config.nationality.hasItem ) {
              const varlidator =  ValidationService.matChingIDNum('idNo', 'nationality');
              this.signForm.setValidators(varlidator);
            }else {
              const varlidator =  ValidationService.matChingIDNum('idNo');
              this.signForm.setValidators(varlidator);
            }
          }
          if (this.config.nationality.hasItem && this.config.nation ) {
            this.signForm.controls['nationality'].valueChanges
              .subscribe((value => {
                if (value === '100000') {
                  this.signForm.controls['nation'].setValue('');
                }else {
                  this.signForm.controls['nation'].setValue('default');
                }
              }));
          }
        }else {
          this.toolsSer.showToast(res.msg);
        }
      });
  }

  showArea() {
    this.modal.show();
  }

  /**
   * 选择籍贯完成
   * @param {PlaceParam} val
   */
  pickerFinish(val: PlaceParam) {
    // console.log(val);
    this.origin.choose = val;
    // 判断有没有城市名，如果没有则是直辖市，只去省级和区域
    const txt = val.cityName ? val.provinceName + ' ' + val.cityName : val.provinceName + ' ' + val.districtName;
    this.origin.text = txt;
    this.config.origin.hasChange = true;
    this.modal.hide();
    this.modal.goBack();
  }

  /**
   * 培训报名
   */
  sign() {
    // if (this.signing) {
    //   return;
    // }
    this.signing = true;
    const allData = this.signForm.controls;
    const data = {
      // userId: this.app.userController().getUserId(),
      orderNumber: this.param.orderNumber,
      goodsSku: this.param.goodsSku,
      courseItemId: this.param.courseItemId,
      courseId: this.param.courseId,
      parentMobile: allData['phone'].value,
      name: allData['name'].value.replace(/(^\s*)|(\s*$)/g, ""),
    };
    this.fields.forEach(e => {
      if (e.fieldName !== 'origin' && e.fieldName !== 'nation' && e.fieldName !== 'idNo') {  // 民族、证件号、籍贯需要处理的
        if (e.fieldName === 'parentName') {  // 如果是姓名和家长姓名，手动去掉字符两端空格
          const tempValue = this.signForm.controls[e.fieldName].value.replace(/(^\s*)|(\s*$)/g, "");
          data[e.fieldName] = tempValue;
        }else {
          data[e.fieldName] = this.signForm.controls[e.fieldName].value;
        }
      }else if (e.fieldName === 'idNo') {  // 输入证件时候分证件号和证件类型
        data['idType'] = this.signForm.controls['idNo'].value['certificate'];
        data['idNo'] = this.signForm.controls['idNo'].value['num'];
      }else if ( e.fieldName === 'origin' || e.fieldName === 'nation' ) {  // 填民族和籍贯时候，如果要选国籍，则国籍不等于中国才取数据
        if ( !this.signForm.controls['nationality'] ||  this.signForm.controls['nationality'].value === '100000') {
          // 拼装籍贯的id
          const province = this.origin.choose.provinceId;
          const city = this.origin.choose.cityId ? this.origin.choose.cityId : this.origin.choose.districtId;
          if (e.fieldName === 'origin') {
            data['origin'] = province + ',' + city;
          }
          if (e.fieldName === 'nation') {
            data['nation'] = this.signForm.controls['nation'].value;
          }
        }
      }
    });
    // this.app.loadingController().present('');
    this.toolsSer.showLoading();
    this.signUpService.trainAdd(data).subscribe(res => {
      this.signing = false;
      // this.app.loadingController().dismiss();
      this.toolsSer.hideLoading();
      if (res.result === '0') {
        // if (this.param.signupFee === 0 || this.param.signupFee < 0 ) {
        //   // this.app.paymentController().goToPayResult(this.param.orderNumber);
        //   this.router.navigate(['/payment/result'], { queryParams : { mchOrderNumber: this.param.orderNumber }});
        // }else {
        //   // this.app.paymentController().goToPaymentPage(this.param.orderNumber);
        //   this.router.navigate(['/payment'], { queryParams : { orderNumber: this.param.orderNumber }});
        // }
        this.signUpService.goToPayOrResult(res.data, this.param.orderNumber);
      }else if (res.result === '40014') {
        // this.app.toastController().prensent('该商品已下架');
        this.toolsSer.showToast('该商品已下架');
      }else {
        // this.app.toastController().prensent(res.msg);
        this.toolsSer.showToast(res.msg);
      }
    });
  }
  // 根据籍贯 判断 按钮的 状态
  checkOrigin(): boolean {
    if (this.config.origin.hasItem && !this.config.origin.hasChange) {  // 如果有籍贯 并且籍贯没有被选过
      if (this.config.nationality.hasItem && this.signForm.controls['nationality'].value !== '100000' ) {  // 如果有国籍并且不是中国就允许
        return true;
      }else {
        return false;
      }
    }else {  // 没有籍贯直接过
      return true;
    }
  }
  /**
   * 根据类型判断添加 control
   * @param {string} type
   * @returns {FormControl}
   */
  addFormControl(type: string): FormControl {
    let validator, control;
    switch (type) {
      case 'sex' :
        validator = [Validators.required];
        control = new FormControl('', validator);
        return control;
      case 'birthday' :  // 生日
        validator = [Validators.required];
        control = new FormControl('', validator);
        return control;
      case 'parentName' :  // 家长名称
        validator = [Validators.required, ValidationService.nickNameSpaceValidator];
        control = new FormControl('', validator);
        return control;
      case 'idNo' :  // 证件号
        // validator = [Validators.required, Validators.maxLength(30), ValidationService.nameValidator];
        // control = new FormControl(['', validator]);
        const numValidator = [Validators.required, Validators.maxLength(20), ValidationService.certificateValidator];
        control = this.formBuilder.group( {
          'num': new FormControl('', numValidator),
          'certificate' :  new FormControl('', [Validators.required]),
        });
        return control;
      case 'nation' :  // 民族
        validator = [Validators.required, Validators.maxLength(20)];
        control = new FormControl('', validator);
        return control;
      case 'school' :  // 学校
        validator = [Validators.required, Validators.maxLength(40)];
        control = new FormControl('', validator);
        return control;
      case 'sportItem' :  // 运动项目
        validator = [Validators.required, Validators.maxLength(200)];
        control = new FormControl('', validator);
        return control;
      case 'remark' :  // 备注
        validator = [Validators.required, Validators.maxLength(200)];
        control = new FormControl('', validator);
        return control;
      case 'awardsItem' :  // 获奖
        validator = [Validators.required, Validators.maxLength(200)];
        control = new FormControl('', validator);
        return control;
      case 'address' :  // 地址
        validator = [Validators.required, Validators.maxLength(200)];
        control = new FormControl('', validator);
        return control;
      case 'weight' :  // 体重
        validator = [Validators.required, Validators.maxLength(3)];
        control = new FormControl('', validator);
        return control;
      case 'height' :  // 身高
        validator = [Validators.required, Validators.maxLength(3)];
        control = new FormControl('', validator);
        return control;
      case 'origin' :  //  籍贯
        validator = [Validators.required];
        control = new FormControl('', validator);
        return control;
      case 'nationality' :  // 国籍
        validator = [Validators.required];
        control = new FormControl('', validator);
        return control;
      case 'trait' :  // 特点
        validator = [Validators.required, Validators.maxLength(200)];
        control = new FormControl('', validator);
        return control;
      case 'email' :  // 邮箱
        validator = [Validators.required, Validators.maxLength(100)];
        control = new FormControl('', validator);
        return control;
    }
  }
  // setFormItemConfig(fields: TrainCourseSignupFields[], data: any){
  //   fields
  // }
}
